use std::thread;
use std::time::Duration;

struct Cacher<T>
    where T: Fn(u32) -> u32 {
    calculation: T,
    value: Option<u32>,
}

impl<T> Cacher<T> where T: Fn(u32) -> u32 {
    fn new(calculation: T) -> Cacher<T> {
        Cacher { calculation, value: None }
    }
    fn value(&mut self, arg: u32) -> u32 {
        match self.value {
            Some(v) => v,
            None => {
                let v = (self.calculation)(arg);
                self.value = Some(v);
                v
            }
        }
    }
}

pub fn main() {
    // let closure = |num| {
    //     println!("慢慢地计算...");
    //     thread::sleep(Duration::from_secs(2));
    //     num
    // };
    let mut closure = Cacher::new(|num| {
        println!("慢慢地计算...");
        thread::sleep(Duration::from_secs(2));
        num
    });
    println!("{}", closure.value(2));
    println!("{}", closure.value(2));
}